define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    var modals = require("./template/modal.html");
    var fn = require("./template/fn.html");
    var classes = require("./template/classes.html");
    var goods = require("./template/goods.html");
    var actpage = require("./template/actpage.html");
    exports.init = function(el,button) {
        $("#ajaxModalLink").remove();
        var $modal = $('<div class="modal fade" id="ajaxModalLink"><div class="modal-body "></div></div>');
        $(document).append($modal);
        $modal.modal();
        var path=button.data("path"),types=button.data("type"),title="选择链接",ctype=button.data("select") || "fn";
        if(types=="copy"){
            title="复制链接";
        }
        var data={
            "path":path,
            "types":types,
            "ctype":ctype,
            "title":title
        }
        $modal.append2(template.compile(modals)(data),function(){
            var id=$(".nav-tabs a[data-type="+ctype+"]",$modal).data("id");
            var $fn=$("#"+id,$modal);
            init(path.format(ctype),{},$fn,ctype,types);
        });
        $('a[data-toggle="tab"]',$modal).on('show.bs.tab', function (e) {
            var $this=$(e.target),id=$this.data("id"),$alllink_list=$("#"+id).find(".js_alllink_list");
            if($alllink_list.length>0){
                $alllink_list.html('<i class="fa fa-spinner fa-spin"></i>');
            }else{
              $("#"+id).html('<i class="fa fa-spinner fa-spin"></i>');  
            }
        })
        $('a[data-toggle="tab"]',$modal).on('shown.bs.tab', function (e) {
            var $this=$(e.target),id=$this.data("id"),type=$this.data("type"),
            $alllink_list=$("#"+id).find(".js_alllink_list");
            if($alllink_list.length>0){
                init(path.format(type),{},$alllink_list,type,types);
            }else{
                init(path.format(type),{},$("#"+id),type,types);
            }
            
        })
        function init(path,data,target,type,types){
            method.post(path, function(data) {
                if (config.issucceed(data)) {
                    data.types=types;
                    switch(type){
                        case "fn":target.html(template.compile(fn)(data));
                            break;
                        case "classes":target.html(template.compile(classes)(data));
                            break;
                        case "actpage":target.html(template.compile(actpage)(data));
                            break;
                        case "goods":
                            data.data.pagelist=pageDate(data.data);
                            target.html(template.compile(goods)(data));
                            break;
                    }
                    var $copy = $(".js_link_copy_text", document);
                    $copy.length > 0 && require.async('zeroclipboard', function(a) {
                        ZeroClipboard.setDefaults({
                            moviePath: "/assets/swf/zeroclipboard.swf"
                        });

                        $.each($copy, function(i) {
                            var html='<button class="btn btn-default js_link_copy btn-sm" id="{0}" type="button" data-clipboard-target="{2}" data-clipboard-text="{1}">复制链接<\/button>  <span class="alert copy-success  alert-success hd " style="position: absolute;left: -173px;top:-3px;">复制成功,请粘帖到您需要的地方<\/span>';
                            if($(this).data("icon")){
                                html='<i id="{0}" data-clipboard-target="{2}" data-clipboard-text="{1}" class="fa fa-copy js_link_copy"><\/i><span class="alert copy-success  alert-success hd " style="position: absolute;left: -173px;top:-3px;">复制成功,请粘帖到您需要的地方<\/span>'
                            }
                            var $id = "copy_button{0}".format(i),
                                _tmp = html,
                                $this = $(this),
                                v = $this.text().trim(),
                                $iid = $this.attr("id");
                            if ($iid) {
                                $this.after(_tmp.format($id, "", $iid))
                            } else {
                                $this.append(_tmp.format($id, v))
                            };
                            var el = $("#" + $id);
                            var clip = new ZeroClipboard(el);
                            var success = function(el) {
                                var span = el.nextAll("span.copy-success");
                                span.show();
                                setTimeout(function() {
                                    span.fadeOut()
                                }, 1000);
                                setTimeout(function(){
                                    $("#ajaxModalLink").modal("hide");
                                },2000);
                            };
                            clip.on('complete', function(client, args) {
                                success($(client.options.button))
                            })
                        })
                        $modal.on("click", "button.js_link_copy", function() {
                            var $this = $(this),
                                v = $this.data("clipboard-text").trim();
                            if ($.browser.msie) {
                                window.clipboardData.setData("Text", v);
                                success($this);
                            } else {
                                prompt('按下 Ctrl+C 复制到剪贴板', v)
                            }
                        })

                    });
                }else{
                    config.msg.error(data.message);
                }
            }, config.lang.exception,false,data);
        }

        function pageDate(data){
            var pagelist=[],total=data.totalPage,current=data.currentPage;
            if(total>0){
                if(total-current>=2){
                    var start=1,end=5;
                    start=(current-2)>0?(current-2):1;
                    end=start+4;
                    for(var i=start;i<=end;i++){
                        if(i>0&&i<=total){
                            pagelist.push(i);
                        }
                    }
                }else{
                    var start=1,end=5;
                    end=(current+2)<=total?(current+2):total;
                    start=end-4;
                    for(var i=start;i<=end;i++){
                        if(i>0&&i<=total){
                            pagelist.push(i);
                        }
                    }
                }
            }
            return pagelist;
        }
        $modal.on("click",".js_alllink_select",function(){
            var $this=$(this),id=$this.data("id"),url=$this.data("link"),
            name=$this.data("name");
            button.prev("input[type='text']").val(url);
            button.prevAll("input[type='hidden']").val(id);
            button.nextAll("div").html(name).attr("title",name);
            button.next("input[type='text']").val(name);
            $modal.modal("hide");
        });
        $modal.on("click","footer[data-type='ajaxPage'] a",function(){
            var $this=$(this),$li=$this.closest('li'),flag=$li.hasClass('disabled'),
            active=$li.hasClass('active'),$tab=$this.closest("div.tab-pane"),id=$tab.attr("id"),
            $form=$tab.find("form"),type=$form.data("type"),path=$form.data("path").format(type),
            $page=$(".js_alllink_page",$form),$alllink_list=$tab.find(".js_alllink_list"),
            pagenum=$this.data("pageNum");
            path+="&submittype=page";
            if(!flag&&!active){
                $page.val(pagenum);
               $modal.find("footer[data-type='ajaxPage'] li.active").removeClass("active");
                $li.addClass('active');
                var data=$form.serialize();
                if($alllink_list.length>0){
                    init(path,data,$alllink_list,type,types);
                }else{
                    init(path,data,$tab,type,types);
                }
            }
        });
        $modal.on("click","button[data-type='ajaxSearch']",function(){
            var $this=$(this),$tab=$this.closest("div.tab-pane"),$form=$this.closest('form'),
            type=$form.data("type"),path=$form.data("path").format(type),$page=$(".js_alllink_page",$form),
            $alllink_list=$tab.find(".js_alllink_list");
            $page.val(1);
            var data=$form.serialize();
            path+="&submittype=search";
            if($alllink_list.length>0){
                init(path,data,$alllink_list,type,types);
            }else{
                init(path,data,$tab,type,types);
            }
    });
    }
});